//
//  CalenderManager.m
//  CalenderDemo
//
//  Created by wr on 2018/7/20.
//  Copyright © 2018年 stzen. All rights reserved.
//

#import "CalenderManager.h"
#import "CalenderModel.h"

@interface CalenderManager()
@property(nonatomic, strong) NSCalendar *greCalender;
@property(nonatomic, strong) NSDate *currentDate;
@end

@implementation CalenderManager

#pragma mark - Init

- (instancetype)init {
    self = [super init];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)commonInit {
    self.greCalender = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    self.currentDate = [NSDate date]; // current date
}

#pragma mark - Public method

- (NSArray *)getCalendarDataSourceWithLimitedMonth:(NSUInteger)limitedMonth {
    NSMutableArray *resultArray = [[NSMutableArray alloc]init];
    
    NSDateComponents *components = [self dateToComponents:self.currentDate];
    components.day = 1;
    components.month -= 1; // 当前月开始向后
    NSInteger i = 0;
    for(i = 0;i < limitedMonth;i++) {
        components.month++;
        CalenderHeaderModel *headerItem = [[CalenderHeaderModel alloc] init];
        NSDate *date = [self componentsToDate:components];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat: @"yyyy年MM月"];
        NSString *dateString = [dateFormatter stringFromDate:date];
        headerItem.headerText = dateString;
        headerItem.dateItems = [self getCalendarItemArrayWithDate:date section:i];
        [resultArray addObject:headerItem];
    }
    return resultArray;
}

#pragma mark - <#mark#>
/**
 * 每一天的数据源
 */
- (NSArray *)getCalendarItemArrayWithDate:(NSDate *)date section:(NSUInteger)section {
    NSMutableArray *resultArray = [[NSMutableArray alloc]init];
    NSInteger tatalDays = [self getCurrentMonthDays:date];
    NSInteger firstDay = [self startDayOfWeek:date];
    
    NSDateComponents *components = [self dateToComponents:date];
    
    // 判断日历有多少列
    NSInteger tempDay = tatalDays + (firstDay - 1);
    NSInteger column = 0;
    if(tempDay % 7 == 0){
        column = tempDay / 7;
    } else {
        column = tempDay / 7 + 1;
    }
    
    NSInteger i = 0;
    NSInteger j = 0;
    components.day = 0;
    for(i = 0;i < column;i++) {
        for(j = 0;j < 7;j++) {
            if(i == 0 && j < firstDay - 1) {
                CalenderModel *calendarItem = [[CalenderModel alloc]init];
                calendarItem.year = 0;
                calendarItem.month = 0;
                calendarItem.day = 0;
//                calendarItem.chineseCalendar = @"";
//                calendarItem.holiday = @"";
                calendarItem.week = -1;
                calendarItem.dateInterval = -1;
                [resultArray addObject:calendarItem];
                continue;
            }
            components.day += 1;
            if(components.day == tatalDays + 1) {
                i = column;// 结束外层循环
                break;
            }
            
            CalenderModel *calendarItem = [[CalenderModel alloc]init];
            calendarItem.year = components.year;
            calendarItem.month = components.month;
            calendarItem.day = components.day;
            calendarItem.week = j;
            NSDate *date = [self componentsToDate:components];
            // 时间戳
            calendarItem.dateInterval = [self dateToInterval:date];
//            if(_startDate == calendarItem.dateInterval)
//            {
//                _startIndexPath = [NSIndexPath indexPathForRow:0 inSection:section];
//            }
//            [self setChineseCalendarAndHolidayWithDate:components date:date calendarItem:calendarItem];
            
            [resultArray addObject:calendarItem];
        }
    }
    return resultArray;
}

#pragma mark - Utils

/**
 * 获取当前月份有多少天
 */
- (NSInteger)getCurrentMonthForDays {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:[NSDate date]];
    NSUInteger numberOfDaysInMonth = range.length;
    return numberOfDaysInMonth;
}

/**
 * 计算某个月有多少天
 */
- (NSUInteger)getCurrentMonthDays:(NSDate *)date {
    return [self.greCalender rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date].length;
}

/**
 * 计算某个月的第一天是周几
 */
- (NSUInteger)startDayOfWeek:(NSDate *)date {
    NSDate *startDate = nil;
    BOOL result = [self.greCalender rangeOfUnit:NSMonthCalendarUnit startDate:&startDate interval:NULL forDate:date];
    if (!result) {
        return 0;
    }
    return [self.greCalender ordinalityOfUnit:NSDayCalendarUnit inUnit:NSWeekCalendarUnit forDate:startDate];
}

/**
 * 日期转时间戳
 */
- (NSInteger)dateToInterval:(NSDate *)date {
    return (long)[date timeIntervalSince1970];
}

+ (NSDateComponents *)currentDateCompoent {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:[NSDate date]];
    return dateComponent;
}

/**
 * NSDate to NSDateComponents
 */
- (NSDateComponents *)dateToComponents:(NSDate *)date {
    NSDateComponents *components = [self.greCalender components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:date];
    return components;
}

/**
 * NSDateComponents to NSDate
 */
- (NSDate *)componentsToDate:(NSDateComponents *)components {
    components.hour = 0;
    components.minute = 0;
    components.second = 0;
    NSDate *date = [self.greCalender dateFromComponents:components];
    return date;
}


@end
